<template>
  <div style="font-family: PingFang SC; font-weight: 300; font-size: 14px; color: #000000">
    淘宝账号
  </div>
  <div class="h-[352px] my-2 pl-1 overflow-x-hidden overflow-y-auto" ref="containerRef">
    <Affix :target="() => containerRef">
      <Flex class="bg-[white] text-center" justify="space-between" gap="small">
        <div class="w-[8%] text-[#999999] text-[12px] text-nowrap">序号</div>
        <div class="w-[24%] text-[#999999] text-[12px]">昵称</div>
        <div class="w-[21%] text-[#999999] text-[12px]">逛逛ID</div>
        <div class="w-[20%] text-[#999999] text-[12px]">领域</div>
        <div class="w-[20%] text-[#999999] text-[12px]">AgentID</div>
        <div class="w-[7%] text-[#999999] text-[12px]"></div>
      </Flex>
    </Affix>
    <template v-for="(account, index) in accountList" :key="index">
      <Flex class="mt-3" justify="space-between" :gap="5">
        <div class="w-[8%]">
          <AInput
            class="text-[12px] text-center px-1 rounded-none"
            v-model:value="account.sort"
            @blur="() => handleSubmit(account)"
          />
        </div>
        <div class="w-[24%]">
          <AInput
            class="text-[12px] px-1 rounded-none"
            v-model:value="account.nick_name"
            @blur="() => handleSubmit(account)"
          />
        </div>
        <div class="w-[21%]">
          <AInput
            class="text-[12px] px-1 rounded-none"
            v-model:value="account.guang_id"
            @blur="() => handleSubmit(account)"
            :readonly="!!account.id"
          />
        </div>
        <div class="w-[20%]">
          <AInput
            class="text-[12px] px-1 rounded-none"
            v-model:value="account.domain"
            @blur="() => handleSubmit(account)"
          />
        </div>
        <div class="w-[20%]">
          <AInput
            class="text-[12px] px-1 rounded-none"
            v-model:value="account.agent_id"
            @blur="() => handleSubmit(account)"
            :readonly="!!account.id"
          />
        </div>
        <div class="w-[8%] text-center">
          <Popconfirm
            placement="left"
            :title="'删除' + account.nick_name + '?'"
            :open="account.visible"
            ok-text="是"
            cancel-text="否"
            @openChange="(bool) => handleDeleteVisibleChange(bool, account)"
            @confirm="() => handleDelete(account)"
            @cancel="
              () => {
                account.visible = false;
              }
            "
          >
            <img
              :src="Delete"
              class="inline-block select-none w-[15px] h-[15px] cursor-pointer mt-1"
            />
          </Popconfirm>
        </div>
      </Flex>
    </template>
    <div class="w-full mt-4 text-[14px] text-right">
      <Affix :offset-bottom="20">
        <AButton
          class="w-[110px] bg-[#001428] text-[#FFFFFF] text-[15px] mr-3"
          type="primary"
          @click="handleAdd"
        >
          <template #icon
            ><img
              :src="Add"
              class="inline-block select-none w-[18px] h-[15px] mt-[-2px] mr-1" /></template
          >新增一条</AButton
        >
      </Affix>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Flex, Affix, Popconfirm, message } from 'ant-design-vue';
import Add from '@main/assets/images/workflow/add.webp';
import Delete from '@main/assets/images/workflow/delete.webp';
import {
  getTaoBaoAccountListApi,
  addTaoBaoAccountApi,
  updateTaoBaoAccountApi,
  updateTaoBaoAccountSortApi,
  deleteTaoBaoAccountApi
} from '@main/service/setting';
import type {
  getTaoBaoAccountListReq,
  taoBaoAccount,
  addTaoBaoAccountReq,
  updateTaoBaoAccountReq
} from '@main/service/setting/type';

type taoBaoAccountTable = taoBaoAccount & {
  originData?: taoBaoAccount;
  visible: boolean; // 用于控制 Popconfirm 的显示
};

const accountList = ref<taoBaoAccountTable[]>([]);
const containerRef = ref();

const handleSubmit = (account: taoBaoAccountTable) => {
  if (
    account.sort === '' ||
    account.nick_name === '' ||
    account.guang_id === '' ||
    account.domain === '' ||
    account.agent_id === ''
  ) {
    // 如果有空值则不提交
    return;
  }

  if (account.id) {
    if (
      account.sort === account.originData?.sort &&
      account.domain === account.originData?.domain &&
      account.nick_name === account.originData?.nick_name &&
      account.guang_id === account.originData?.guang_id &&
      account.agent_id === account.originData?.agent_id
    ) {
      // 如果数据没有变化，则不提交
      return;
    }
    if (account.sort != account.originData?.sort) {
      updateTaoBaoAccountSortApi({ id: account.id, sort: account.sort })
        .then(() => {
          message.success('序号更新成功');
          account.originData!.sort = account.sort;
          window.clientAppSdk.ipc.ipcRenderer.send('rc:router-page-data-change', ['DaRen']);
        })
        .catch(() => message.error('账号更新失败'));
      return;
    }

    // 更新账号
    const updateAccount: updateTaoBaoAccountReq = {
      id: account.id,
      nick_name: account.nick_name,
      domain: account.domain
    };
    updateTaoBaoAccountApi(updateAccount)
      .then(() => {
        message.success('账号更新成功');
        account.originData!.domain = account.domain;
        account.originData!.nick_name = account.nick_name;
        account.originData!.guang_id = account.guang_id;
        window.clientAppSdk.ipc.ipcRenderer.send('rc:router-page-data-change', ['DaRen']);
      })
      .catch(() => message.error('账号更新失败'));
  } else {
    // 新增账号
    const newAccount: addTaoBaoAccountReq = {
      sort: account.sort,
      guang_id: account.guang_id,
      nick_name: account.nick_name,
      domain: account.domain,
      agent_id: account.agent_id
    };
    addTaoBaoAccountApi([newAccount]).then((res) => {
      if (res.create_id > 0) {
        message.success('账号新增成功');
        account.id = res.create_id;
        account.originData = newAccount;
        window.clientAppSdk.ipc.ipcRenderer.send('rc:router-page-data-change', ['DaRen']);
      }
    });
  }
};

const handleDelete = (account: taoBaoAccount) => {
  accountList.value = accountList.value.filter((item) => item !== account);
  if (account.id) {
    deleteTaoBaoAccountApi(account.id)
      .then(() => message.success('账号删除成功'))
      .catch(() => message.error('账号删除失败'));
  }
};

const handleAdd = () => {
  accountList.value.push({
    sort: '',
    nick_name: '',
    guang_id: '',
    domain: '',
    agent_id: '',
    visible: false
  });
};

const handleDeleteVisibleChange = (bool: boolean, account: taoBaoAccountTable) => {
  if (!bool) {
    return;
  }

  if (account.nick_name != '') {
    account.visible = true;
  } else handleDelete(account);
};

onMounted(() => {
  getTaoBaoAccountList();
});

const getTaoBaoAccountList = () => {
  const params: getTaoBaoAccountListReq = { pageNumber: 1, pageSize: 1000 };
  getTaoBaoAccountListApi(params).then((res) => {
    accountList.value = res.items.map((item) => ({
      ...item,
      originData: { ...item },
      visible: false
    })) as taoBaoAccountTable[];
  });
};
</script>
<style lang="less" scoped></style>
